package com.lw.alarm.filter;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.druid.util.StringUtils;
import com.lw.alarm.model.AlarmNoticeLog;
import com.lw.alarm.model.AlarmServer;
import com.lw.alarm.model.enums.NoticeResult;
import com.lw.alarm.model.enums.NoticeWay;
import com.lw.alarm.service.AlarmNoticeLogService;
import com.lw.alarm.util.compent.EmailHelper;

/**
 * 
 * @Description: 责任链中的邮件处理
 * @author wei.liu
 * @date 2017年4月19日 下午2:41:19
 * @version V1.0
 */
public class EmailFilter implements Filter {
	private final static Logger logger = LoggerFactory.getLogger(EmailFilter.class);
	private EmailHelper emailHelper;
	private AlarmNoticeLogService alarmNoticeLogService;

	public EmailFilter(EmailHelper emailHelper, AlarmNoticeLogService alarmNoticeLogService) {
		super();
		this.emailHelper = emailHelper;
		this.alarmNoticeLogService = alarmNoticeLogService;
	}

	@Override
	public void doFilter(AlarmServer request, Response response, FilterChain chain) {

		if (!StringUtils.isEmpty(request.getNoticeEmails())) {
			String[] emails = request.getNoticeEmails().split(",");
			String subject;
			int length = emails.length;
			AlarmNoticeLog record = new AlarmNoticeLog();
			for (int i = 0; i < length; i++) {
				record.setServerId(request.getId());
				record.setServerName(request.getServerName());
				if (request.getStatus() == 0) {
					record.setNoticeType((byte) 1);
					subject = request.getNoticeEmailSubject() + "已经恢复正常";
				} else {
					subject = request.getNoticeEmailSubject() + "异常";
					record.setNoticeType((byte) 0);
				}
				record.setCreateTime(new Date());
				record.setNoticeAddress(emails[i]);
				record.setNoticeWay((byte) NoticeWay.EMAIL.ordinal());
				record.setNoticeResult((byte) NoticeResult.SUCCESS.ordinal());
				try {

					emailHelper.sendSimpleMail(emails[i], subject,
							request.getNoticeContent() + "</br>=======原因如下：==========>" + request.getServerErrorMsg());

				} catch (Exception e) {
					record.setNoticeResult((byte) NoticeResult.SUCCESS.ordinal());
					logger.error("发送邮件失败！", e);
				}
				logger.debug("========>开始记录发送邮件日志");
				alarmNoticeLogService.insert(record);
			}
		}
		chain.doFilter(request, response, chain);
		response.responseStr.concat("---EmailFilter()");

	}

}
